//
//  WKBaseViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/9.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  WKWebView基础类

import UIKit
import WebKit

import CoreTelephony

var _symbolForH5chosssedef : String = "false"

var shopList : String?


/// 当用户留言完毕后，出发此函数，跳转至交流区最初页面
protocol WKBaseDelegate {
    func server()
}

class WKBaseViewController: BaseViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UIScrollViewDelegate {
    
    var webView: WKWebView!
    
    static let shared = WKBaseViewController()
    
    
    // MARK:- 分享视图
    var shareView    :YSJShareView!
    
    // MARK:- 全局链接变量
    var url : String = ""
   
    // MARK:- 为网络状态
    var netStatus : String = ""
    
    // MARK:- 刷新控件
    var refreshControl = UIRefreshControl()
    // MARK:- 进度条
    var progressView = UIProgressView()
    
    // MARK:- 网络加载的路径
    var urlRequestCache = NSURLRequest()
    
    // MARK:- 分享变量
    var titleStr : String = ""
    var desc : String = ""
    var link : String = ""
    var imgURL : String = ""
    
    // MARK:- 检查刷新加载
    var situationMark = "loadFailed"
    
    // MARK:- 权限按钮
    let AutoCellularbtn = UIImageView()
    
    // MARK:- 刷新图片
    var imgView = UIImageView()
    
    // MARK:- token
    var token : String = ""
    
    // MARK:- 分享视图
//    var viewController = ShareViewController()
    
    //代理
    var wkDelegate : WKBaseDelegate?
    
    /// 断网图片单机刷新事件
    func imgSEL() -> Void {
        
        view.addSubview(self.webView)
        
        self.webView.load(self.urlRequestCache as URLRequest)
    }
    
    // MARK:- 移除蜂窝权限图片，界面消失的时候
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        AutoCellularbtn.removeFromSuperview()
        
    
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        ///先检查网络类型，只在蜂窝网络状态下进行提示---用户开启网络权限
        // MARK:- 根据是否有网络状态加载断网图片
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            ///不是wifi，进行检查
            if result != "wifi" {
                ///应用启动后，检测应用中是否有联网权限
                if #available(iOS 9.0, *) {
                    
                    let culluarData = CTCellularData()
                    
                    culluarData.cellularDataRestrictionDidUpdateNotifier = { (state : CTCellularDataRestrictedState) -> Void in
                        
                        ///网络受限
                        if state.hashValue == 1 {
                            
                            DispatchQueue.main.async {
                                self.AutoCellularbtn.frame = CGRect(x:SW * 0.25 , y: SH * 0.25, width: SW * 0.5, height: SW * 0.5)
                                
                                self.AutoCellularbtn.image = UIImage.init(named: "sulution")
                                self.AutoCellularbtn.isUserInteractionEnabled = true
                                
                                let soluGes = UITapGestureRecognizer.init(target: self, action: #selector(WKBaseViewController.gotoSet))
                                
                                self.AutoCellularbtn.addGestureRecognizer(soluGes)
                                
                                self.view.addSubview(self.AutoCellularbtn)
                                
                                return
                            }
                            
                        ///网络未受限
                        } else {
                            //取出本地token，进行拼接,token为空不为空，均传到服务器
                            if (localSave.object(forKey: userToken) != nil) {
                                self.token = localSave.object(forKey: userToken) as! String
                                
                            } else {
                                self.token = ""
                            }
                            
                        }
                        
                    }
                
                }
            ///是wifi，正常执行
            } else if result == "notReachable" {

            }
        }
    
    
        //取出本地token，进行拼接,token为空不为空，均传到服务器
        if (localSave.object(forKey: userToken) != nil) {
            token = localSave.object(forKey: userToken) as! String
            
        } else {
            token = ""
        }
    
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.SETUI()
    }
    
    
    // MARK:- 网络开始请求
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {

        self.navigationItem.title = "加载中~~~"
        
        if self.webView == nil {
         self.SETUI()
            return
        } else {
//            self.webView.isUserInteractionEnabled = false
            return
        }
    }
    
    // MARK:- 监听进度条值变化
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") { // listen to changes and updated view
            progressView.isHidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        }
    }
    
    // MARK:- wkwebview代理方法
    /// 没网络发起
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {

        self.navigationItem.title = "请检查网络"
        
        self.webView.isUserInteractionEnabled = true

        //赋值，表示失败，供刷新使用
        self.situationMark = "true"
        
        netStatus = "false"
        
        self.setNetFail()
        
        //根据是否有网络状态加载断网图片
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            if result == "notReachable" {
                self.imgView.image = UIImage.init(named: "lostNet")
                self.view.addSubview(self.imgView)
                
            } else {
                return
            }
        }
        
        refreshControl.endRefreshing()


    }
    
    // MARK:- 允许拦截
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        decisionHandler(.allow)
    }
    
    // MARK:- webview加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        refreshControl.endRefreshing()
        
        ///允许交互
        self.webView.isUserInteractionEnabled = true
        
        //改变刷新标识符
        self.situationMark = "false"
        
        netStatus = "true"
        
        //移除没有网络提示图片
        DispatchQueue.main.async {
            self.imgView.removeFromSuperview()
        }
        
        
        self.progressView.progress = Float(webView.estimatedProgress)
        self.navigationItem.title = self.webView.title
        
        
        //走满进度条，停止选择
        if self.webView.isLoading == false {
            UIView.animate(withDuration: 0.5, animations: {
                self.progressView.alpha = 0
            })
        }
        
    }
    
    

    
    // MARK:- js交互
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let msg = message.name
        

        
        //微信分享
        if  msg == "shareWeixinInfo" {
            
            //将获取到的数据解析成字典
            let messageDic = message.body as! NSDictionary
            
            
            //解析取回的字典数据
            titleStr = messageDic["title"] as! String
            desc = messageDic["desc"] as! String
            link = messageDic["link"] as! String
            imgURL = messageDic["imgUrl"] as! String
            
            
//            viewController = ShareViewController()
//            viewController.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
//            
//            viewController.delegate = self
//
//            self.present(viewController, animated: true, completion: nil)

            shareView = YSJShareView.init(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - 80, width: UIScreen.main.bounds.width, height: 80))
            shareView._delegate = self
            shareView.addItem("QQ", withImage: UIImage(named: "s_QQ")!)
            shareView.addItem("QQ空间", withImage: UIImage(named: "s_QZone")!)
            shareView.addItem("微信朋友圈", withImage: UIImage(named: "wx_Fri")!)
            shareView.addItem("微信好友", withImage: UIImage(named: "wx_Zone")!)
            shareView.layer.cornerRadius = 5
            
            self.view.addSubview(shareView)
            
            shareView.show()
            //微信支付
        } else if msg == "wxpay" {
            
            
            
            let wxDic = message.body as! NSDictionary
            
            //XFLog(message: wxDic)
            
            
                ///微信支付
                WXTool.shared.sendWXPay(wxDict: wxDic, _com: { (result) in
            
                    switch result {
                    case "-2":
                        
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        break
                        
                    case "0":
                        
                        self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                        break
                        
                    case "-1":
                        self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                        break
                        
                    default:
                        break
                    }
                    
                    //清除URL保存的值
                    mainIndexArray.removeAllObjects()
                    fwqArray.removeAllObjects()
                    commuArray.removeAllObjects()
                    shoppingCarArray.removeAllObjects()
                    jiaoYIArray.removeAllObjects()
                    zhongjiangArray.removeAllObjects()
                    duihuanArray.removeAllObjects()
                    fenxiangArray.removeAllObjects()
                    
                })


            ///支付宝
        } else if msg == "alipay" {
            let dic = message.body as! NSDictionary
            
            var signStr = ""
            
            if ((dic["sign"] as? String) != nil) {
                signStr = dic["sign"] as! String
            } else {
                //回调返回值处理
                return
            }
            
            //接收Web支付回调
            PaymenyModel.shared.alipay(orderString: signStr, comfun: { (result) in

                
                switch result {
                case "用户中途取消":
                    
                    self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                    break
                    
                case "网页支付成功":
                    
                    self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                    break
                    
                case "正在处理中":
                    CustomAlertView.shared.alertWithTitle(strTitle: "正在处理中")
                    break
                    
                case "网络连接出错":
                    CustomAlertView.shared.alertWithTitle(strTitle: "网络连接出错")
                    //                    self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
                    break
                    
                case "订单支付失败":
                    self.navigationController?.pushViewController(PayFailViewController(), animated: true)
                    break
                default:
                    break
                }
                

                //清除URL保存的值
                mainIndexArray.removeAllObjects()
                fwqArray.removeAllObjects()
                commuArray.removeAllObjects()
                shoppingCarArray.removeAllObjects()
                jiaoYIArray.removeAllObjects()
                zhongjiangArray.removeAllObjects()
                duihuanArray.removeAllObjects()
                fenxiangArray.removeAllObjects()
            })
            
            ///接收appdelegate代理传回的值
            NotificationCenter.default.addObserver(self, selector: #selector(WKBaseViewController.info(notification:)), name: NSNotification.Name(rawValue: "123"), object: nil)
            
        } else if msg == "gotoCart" {
            
            jumpToShop()
        } else if msg == "login" {
            
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(LoginView(), animated: true)
            self.hidesBottomBarWhenPushed = false
            
            shoppingCarArray.add(message.body)
            
        } else if msg == "submit" {

            self.wkDelegate?.server()
            
        } else if msg == "detailRocord" {
            
            jumpDetaiRecord()
            
        } else if msg == "backToMain" {

            backToMain()
        
            //调到购物车
        } else if msg == "getCartList" {
            
            shopList = message.body as? String

            
        ///选择地址
        } else if msg == "chooseAddress" {
            
            
            NotificationCenter.default.addObserver(self, selector: #selector(chuangei(notification:)), name: NSNotification.Name(rawValue: "addressSet"), object: nil)
        
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(DetailAddressVC(), animated: true)
            
        } else if msg == "refreshWeb" {
            
            //XFLog(message: "刷新网页")
            self.webView.reload()
        } else if msg == "personInfo" {
            
            gotoPerson()
        } else if msg == "backToIndex" {
            gotoMain()
        }
        
    }
    
    // MARK:- 收货地址
    func chuangei(notification : Notification) -> Void {
        
         let dic = notification.userInfo
        
        let _adrid = dic?["adrid"] as! String
        
        ///地址编号
        let yinhaoadrid = "\"" + _adrid + "\""
        
        ///名字
        let _name = dic?["name"] as! String
        let yinhaoname = "\"" + _name + "\""
        

        
        let _tel = dic?["tel"] as! String
        let yintel = "\"" + _tel + "\""

        
        let _area = dic?["area"] as! String
        let yinarea = "\"" + _area + "\""

        
        let _address = dic?["address"] as! String
        let yinaddress = "\"" + _address + "\""

        
        let jsonStr : NSString = "{\("\"adrid\"") : \(yinhaoadrid),\("\"name\"") : \(yinhaoname),\("\"tel\"") : \(yintel),\("\"area\"") : \(yinarea),\("\"address\"") : \(yinaddress)}" as NSString
       
        self.webView.evaluateJavaScript("addrCheck('\(jsonStr)')", completionHandler: nil)

        if self.navigationController == nil {
            return
        } else {
            
        }

        
        _symbolForH5chosssedef = "true"
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "addressSet"), object: nil)
    }
    
    
    // MARK:- 交互函数
    /// 返回首页
    func jumpDetaiRecord() -> Void {
        self.navigationController?.pushViewController(ChangedRecordVC(), animated: true)
    }
    
    // MARK:- 返回首页
    func backToMain() -> Void {
        self.webView = nil
        
        //清除URL保存的值
        mainIndexArray.removeAllObjects()
        fwqArray.removeAllObjects()
        commuArray.removeAllObjects()
        shoppingCarArray.removeAllObjects()
        jiaoYIArray.removeAllObjects()
        zhongjiangArray.removeAllObjects()
        duihuanArray.removeAllObjects()
        fenxiangArray.removeAllObjects()
        
        
        let mainVC = MainViewController()
        mainVC.mvc = LoginView()
        UIApplication.shared.keyWindow?.rootViewController = mainVC
    }
    
    // MARK:- 跳转到购物车页面
    func jumpToShop() -> Void {
        
        let mainVC = MainViewController()
        
        UIApplication.shared.keyWindow?.rootViewController = mainVC
        
        let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        
        
        tabBarController.selectedIndex = 2
        //移除先前存储的数组，以免跳转不正确
        shoppingCarArray.removeAllObjects()
        mainIndexArray.removeAllObjects()
    
    }
    
    // MARK:- 刷新函数
    func refreshWebView(sender: UIRefreshControl) {
        
        StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
            
            if result == "notReachable" {
                sender.endRefreshing()

            } else {
                
                //判断是否存在网页，若有，则刷新，没有则不刷新
                if self.webView == nil {
                    
                    
                    sender.endRefreshing()

                    let mainVC = MainViewController()
                    UIApplication.shared.keyWindow?.rootViewController = mainVC
                    
                    let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
                    tabBarController.selectedIndex = 0
                    
                } else if self.situationMark == "true" {
                    
                    //网络标识为没网络，从先前浏览过的网页记录进行查找
                    if mainIndexArray.lastObject != nil {
                        self.webView.load(URLRequest.init(url: URL.init(string: mainIndexArray.lastObject as! String)!))
                        
                    } else if shoppingCarArray.lastObject != nil {
                        self.webView.load(URLRequest.init(url: URL.init(string: shoppingCarArray.lastObject as! String)!))
                        
                    } else if separateArrey.lastObject != nil {
                        self.webView.load(URLRequest.init(url: URL.init(string: separateArrey.lastObject as! String)!))
                    } else {
                        //清除URL保存的值
                        mainIndexArray.removeAllObjects()
                        fwqArray.removeAllObjects()
                        commuArray.removeAllObjects()
                        shoppingCarArray.removeAllObjects()
                        jiaoYIArray.removeAllObjects()
                        zhongjiangArray.removeAllObjects()
                        duihuanArray.removeAllObjects()
                        fenxiangArray.removeAllObjects()
    
                        let mainVc = MainViewController()
                        UIApplication.shared.keyWindow?.rootViewController = mainVc
                    }
                    
                    
                } else if self.situationMark != "true" {
                    
                    self.webView.removeFromSuperview()
                    
                    self.webView.reload()
                    
                    self.view.addSubview(self.webView)
                    
                    sender.endRefreshing()
                }
            }
        }
    }
}



// MARK:- 处理收到内存警告---释放webview
extension WKBaseViewController {
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        self.webView = nil
    }
}

// MARK:- 购物车交互事件
extension WKBaseViewController {
    ///个人中心
    func gotoPerson() -> Void {
        let tabbarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        tabbarController.selectedIndex = 3
        
        Animated.vcWithTransiton(vc: tabbarController, animatedType: "kCATransitionFade", timeduration: 0.5)
    }
    
    ///前往首页
    func gotoMain() -> Void {
        let tabbarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        tabbarController.selectedIndex = 0
        
        Animated.vcWithTransiton(vc: tabbarController, animatedType: "kCATransitionFade", timeduration: 0.5)
    }
    
}

// MARK:- 接收支付宝app接收结果
extension WKBaseViewController {
    func info(notification : NSNotification) -> Void {
        
        let dic = notification.userInfo as! [AnyHashable : NSObject] as NSDictionary
        
        let result = dic["re"] as! String
        
        switch result {
        case "用户中途取消":
            
            self.navigationController?.pushViewController(PayFailViewController(), animated: true)
            break
            
        case "支付成功":
            
            //清楚购物车信息
            shopList = nil
            self.navigationController?.pushViewController(PaySuccessVC(), animated: true)
            break
            
        case "正在处理中":
            CustomAlertView.shared.alertWithTitle(strTitle: "正在处理中")
            break
            
        case "网络连接出错":
            CustomAlertView.shared.alertWithTitle(strTitle: "网络连接出错")
            
            break
            
        case "订单支付失败":
            self.navigationController?.pushViewController(PayFailViewController(), animated: true)
            break
        default:
            break
        }

        //清除URL保存的值
        mainIndexArray.removeAllObjects()
        fwqArray.removeAllObjects()
        commuArray.removeAllObjects()
        shoppingCarArray.removeAllObjects()
        jiaoYIArray.removeAllObjects()
        zhongjiangArray.removeAllObjects()
        duihuanArray.removeAllObjects()
        fenxiangArray.removeAllObjects()


        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "123"), object: nil)
    }
}

// MARK:- 解决蜂窝网受限
extension WKBaseViewController {
    func gotoSet() -> Void {
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(AutoSolVC(), animated: true)
        self.hidesBottomBarWhenPushed = false
        
    }

}

// MARK:- 设置界面
extension WKBaseViewController {
    func SETUI() -> Void {
        // Do any additional setup after loading the view.
        
        ///http://www.jianshu.com/p/879fe48b0eb7
        ///edgesForExtendedLayout------见网页链接
        self.edgesForExtendedLayout = UIRectEdge()
        
        //配置webview
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        //添加交互条目
        //分享到微信
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        
        //微信支付
        userContentController.add(self as WKScriptMessageHandler, name: "wxpay")
        
        //支付宝支付
        userContentController.add(self as WKScriptMessageHandler, name: "alipay")
        
        //登陆
        userContentController.add(self as WKScriptMessageHandler, name: "login")
        
        //跳转到购物车
        userContentController.add(self as WKScriptMessageHandler, name: "gotoCart")
        
        //确认提交建议
        userContentController.add(self as WKScriptMessageHandler, name: "submit")
        
        //交易记录
        userContentController.add(self as WKScriptMessageHandler, name: "detailRocord")
        
        //返回首页
        userContentController.add(self as WKScriptMessageHandler, name: "backToMain")
        
        //购物车列表
        userContentController.add(self as WKScriptMessageHandler, name: "getCartList")
        
        ///选择地址
        userContentController.add(self as WKScriptMessageHandler, name: "chooseAddress")
        
        ///刷新网页 - refreshWeb
        userContentController.add(self as WKScriptMessageHandler, name: "refreshWeb")
        
        ///个人中心
        userContentController.add(self as WKScriptMessageHandler, name: "personInfo")
        
        ///随便逛逛（首页）
        userContentController.add(self as WKScriptMessageHandler, name: "backToIndex")
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        configuration.preferences.javaScriptEnabled = true
        configuration.processPool = WKProcessPool()
        
        
        if self.navigationController == nil {
            return
        }
        
        ///由于设置了edgesForExtendedLayout,防止了页面全部控件向上偏移，所以在子页面数大于2的时候，矫正
        if (self.navigationController?.viewControllers.count)! >= 2 {
            let rect = CGRect(x: 0, y: 0, width: SW, height: SH - 64)
            webView = WKWebView.init(frame: rect, configuration: configuration)
        } else {
            let rect = CGRect(x: 0, y: 0, width: SW, height: SH - 112)
            
            webView = WKWebView.init(frame: rect, configuration: configuration)
        }

        
        ///配置wkwebview代理
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.scrollView.bounces = true
        
//        webView.scrollView.delegate = self
        
        view.addSubview(webView)
        
        //动画过度
        self.webView.alpha = 0
        
        UIView.animate(withDuration: 1.0) {
            self.webView.alpha = 1.0
        }
        
        //添加进度条
        self.progressView = UIProgressView()
        
        self.progressView.frame = view.bounds
        view.addSubview(self.progressView)
        
        //默认进度条
        self.progressView.progressTintColor = UIColor.orange
        
        
        //添加刷新控件
        self.refreshControl = UIRefreshControl()
        
        //设置刷新控件的位置
        let offset = -0
        self.refreshControl.bounds = CGRect(x: refreshControl.bounds.origin.x, y: CGFloat(offset),
                                            width: refreshControl.bounds.size.width,
                                            height: refreshControl.bounds.size.height)
        self.refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
        self.webView.scrollView.addSubview(refreshControl)
        
        //监听KVO
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) // add observer for key path
    }
}

// MARK:- 设置没网络图片
extension WKBaseViewController {
    func setNetFail() -> Void {
        imgView = UIImageView()
        
        //手动设置没网络图片位置
        imgView.frame = CGRect(x:SW * 0.25 , y: SH * 0.25, width: SW * 0.5, height: SW * 0.5)
        
        imgView.image = UIImage.init(named: "lostNet")
        
        imgView.contentMode = UIViewContentMode.scaleAspectFit
        
        let tag = UITapGestureRecognizer.init(target: self, action:#selector(WKBaseViewController.imgSEL))
        
        imgView.isUserInteractionEnabled = true
        
        imgView.addGestureRecognizer(tag)
    }
}

// MARK:- 分享类型
extension WKBaseViewController : YSJShareViewDelegate {
    func shareBtnClick(_ index: Int) {
        switch index {
        case 0:
            
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    MBManager.hideAlert()
                    
                    MBManager.showBriefAlert("请检查网络")
                } else {
                    
                    MBManager.showBriefAlert("加载分享资源中...")
                    
                    XFLog(message: self.link)
                    
                    QQTool.shared.qqShare(title: self.titleStr, desc: self.desc, link: self.link, imgUrl: self.imgURL, type: QQApiURLTargetTypeAudio)
                    
                }
            })
            break
        case 1:
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                    
                } else {
                    
                    MBManager.showBriefAlert("加载分享资源中...")
                    
                    
                    QQTool.shared.qqShare(title: self.titleStr, desc: self.desc, link: self.link, imgUrl: self.imgURL, type: QQApiURLTargetTypeAudio)
                }
            })
            
            break
        case 2:
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                } else {
                    MBManager.showBriefAlert("加载分享资源中...")
                    XFLog(message: self.link)
                    
                    WXTool.shared.shareText(title: self.titleStr, desc:self.desc, link: self.link, imgUrl: self.imgURL, shareType: 1)
                }
            })
            
            break
        case 3:
            StatusBarCheck.shared.networkingStatesFromStatebar(_com: { (result) in
                if result == "notReachable" {
                    MBManager.hideAlert()
                    MBManager.showBriefAlert("请检查网络")
                    
                    
                } else {
                    MBManager.showBriefAlert("加载分享资源中...")
                    
                    XFLog(message: self.link)
                    
                    WXTool.shared.shareText(title: self.titleStr, desc:self.desc, link: self.link, imgUrl: self.imgURL, shareType: 0)
                }
            })
            
            break
        default:
            break
        }
    }
}
